﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Yipusoft.Common.BLL;
using Yipusoft.Common.Model;

using System.Collections.Generic;
using System.Text;
using Yipusoft.Account.Model;
using Yipusoft.Account.BLL;
using System.IO;
using Yipusoft.TownshipEnterprise.BLL;
using Yipusoft.TownshipEnterprise.Model;
using System.Drawing;
using System.Drawing.Imaging;


public partial class TownshipEnterprise_DeviceAdd : System.Web.UI.Page
{

    int _limitwidth = 640;
    int _limitheight = 480;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDepartment();
            BindType();
            BindClass();
            BindCodeItemList(UnitNameList, "ZBQC020000");
            BindCodeItemList(StateList, "ZBQC030000");
            //UnitList.SelectedValue = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
            if (Request.QueryString["DeviceID"] == null)
            {
                if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200500") || Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200501"))
                {
                    ActionTitle.Text = "添加装备器材";

                }
                else
                {
                    Response.Write("<script>alert('没有权限！');history.back(0);</script>");
                    return;
                }


            }
            else
            {
                if (!Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200500") && !Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200502"))
                {
                    Response.Write("<script>alert('没有权限！');history.back(0);</script>");
                    return;
                }
                else
                {
                    ActionTitle.Text = "编辑装备器材";
                    BindData();
                }
            }




        }
    }

    /// <summary>
    /// 绑定各市
    /// </summary>
    void BindDepartment()
    {
        UserInfo userInfo = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
        DepartmentInfo department = Department.GetDepartment(userInfo.DepartmentID);
        if (userInfo.DepartmentID.Substring(0, 4) == "1300")
        {
            DepartmentList.DataSource = Yipusoft.Account.BLL.Department.GetList(" (SUBSTRING(DepartmentID, 5, 3) = '000') and DepartmentID<>'1300000' ");
            DepartmentList.DataBind();
            DepartmentListBind();
        }
        else
        {
            DepartmentList.DataSource = Yipusoft.Account.BLL.Department.GetList(" DepartmentID= '" + department.DepartmentID.Substring(0, 4) + "000' ");
            DepartmentList.DataBind();
            DepartmentListBind();
        }
    }

    private void BindCodeItemList(DropDownList ddl, string parentID)
    {
        ListItem li;
        List<CodeItemInfo> items = CodeItem.GetList("ParentID='" + parentID + "' ORDER BY ItemID,SeqID");
        foreach (CodeItemInfo item in items)
        {
            li = new ListItem();
            li.Text = "".PadRight(2 * (item.ItemLevel - 1), '　') + item.ItemName;
            li.Value = item.ItemID;
            ddl.Items.Add(li);
            BindCodeItemList(ddl, item.ItemID);
        }
    }
/// <summary>
/// 绑定装备类型
/// </summary>
    void BindType()
    {
        DeviceTypeList.DataTextField = "ItemName";
        DeviceTypeList.DataValueField = "ItemID";
        DeviceTypeList.DataSource = CodeItem.GetList(" parentID='ZBQC010000' order by ItemID,SeqID ");
        DeviceTypeList.DataBind();
    }
    private void BindData()
    {
        TownDevicesInfo device = TownDevices.GetTownDevices(new Guid(Request.QueryString["DeviceID"]));

        DepartmentList.SelectedValue = TownBasic.GetTownBasic(new Guid(device.TownBasicID)).DepartmentID.Substring(0, 4) + "000";
        DepartmentListBind();
        UnitList.SelectedValue = device.TownBasicID;
        //CascadingDropDown_Department.SelectedValue = device.DepartmentID.Substring(0, 4) + "000";
        //CascadingDropDown_Unit.SelectedValue = device.DepartmentID;
        if (device.DeviceClass != "")
        {
            DeviceTypeList.SelectedValue = CodeItem.GetCodeItem(device.DeviceClass).ParentID;
            DeviceClassList.SelectedValue = device.DeviceClass;
        }
        DeviceName.Text = device.DeviceName;
        DeviceModel.Text = device.DeviceModel;
        DeviceCount.Text = device.DeviceCount.ToString();
        UnitNameList.SelectedIndex = UnitNameList.Items.IndexOf(UnitNameList.Items.FindByText(device.UnitName));
        Parameters.Text = device.Parameters;
        Price.Text = device.Price.ToString();
        DatePurchase.Text = device.DatePurchase.ToShortDateString();
        DateUse.Text = device.DateUse.ToShortDateString();
        DateProduct.Text = device.DateProduct.ToShortDateString();
        Manufacturer.Text = device.Manufacturer;
        StateList.SelectedIndex = StateList.Items.IndexOf(StateList.Items.FindByValue(device.State));
    }
    private void Insert()
    {

        if(UnitList.Items.Count==0||UnitList.SelectedValue=="")
        {
            Response.Write("<script language=javascript>alert(' 请选择专职队！')</script>");
            return;
        }


        TownDevicesInfo device = new TownDevicesInfo();

        string where = " TownBasicID='" + UnitList.SelectedValue + "' and DeviceClass='" + DeviceClassList.SelectedValue + "' and DeviceName='" + DeviceName.Text + "' and State='" + StateList.SelectedValue + "' ";
        List<TownDevicesInfo> list = TownDevices.GetList(where);
        if (list.Count > 0)
        {
            Prompt.Text = "提示:此装备器材已存在!";
            return;
        }
        try
        {
        
        device.ID = Guid.NewGuid();
        device.TownBasicID = ddlTownBasic.SelectedValue;
        device.DeviceClass = DeviceClassList.SelectedValue;
        device.DeviceName = DeviceName.Text;
        device.DeviceModel = DeviceModel.Text;
        device.DeviceCount = int.Parse(DeviceCount.Text);
        device.UnitName = UnitNameList.SelectedValue;
        device.Parameters = Parameters.Text;
        device.Price = decimal.Parse(Price.Text);
        device.DatePurchase = DateTime.Parse(DatePurchase.Text);
        device.DateUse = DateTime.Parse(DateUse.Text);
        device.DateProduct = DateTime.Parse(DateProduct.Text);
        device.Manufacturer = Manufacturer.Text;
        device.State = StateList.SelectedValue;
        device.TimeLastModified = DateTime.Now;

        }
        catch
        {
            Response.Write("<script language=javascript>alert('填写错误！')</script>");
            return;
        }


       //添加照片--数据库
        TownPicsInfo pic = new TownPicsInfo();
        pic.id = Guid.NewGuid();
        pic.TownBasicInfoID = device.ID;

        //保存图片
        HttpFileCollection files = HttpContext.Current.Request.Files;
        HttpPostedFile file = files.Get("ctl00$ContentPlaceHolder1$WordFile");
        string path = string.Empty;
        string picName = DateTime.Now.ToString("yyyyMMddHHmmssff");
        bool img = SaveImg(picName, "5", file, out path);
        if (!img)
            return ;
        else
        {
            pic.PicDescript = "";
            pic.PicPath = path;
            pic.TownPicstypeID = "h";
            bool b1 = TownPics.Insert(pic);
            if (!b1)
            {

                string allPath = Request.MapPath("") + "\\" + @path;
                try
                {
                    File.Delete(allPath);
                }
                catch
                { }
                Response.Write("<script language=javascript>alert('图片上传失败！')</script>");
                return ;
            }
        }
       device.Picture = path;
        bool b_add=TownDevices.Insert(device);

        //EventLogInfo log = new EventLogInfo();
        //log.EventTime = DateTime.Now;
        //log.EventType = 1;
        //log.EventData = "添加新记录";
        //log.ItemID = id.ToString();
        //log.ItemName = "Devices";
        //log.ItemFullUrl = "DeviceNew.aspx";
        //log.CreatedBy = Context.User.Identity.Name;
        //log.CreatedTime = DateTime.Now;
        //log.UserIP = Request.UserHostAddress;
        //EventLog.Insert(log);
        if(b_add)
        Prompt.Text = "提示：添加成功！";
        else
             Prompt.Text = "提示：添加失败！";
    }
    private void Update()
    {


        if (UnitList.Items.Count == 0 || UnitList.SelectedValue == "")
        {
            Response.Write("<script language=javascript>alert(' 请选择专职队！')</script>");
            return;
        }

        TownDevicesInfo device = TownDevices.GetTownDevices(new Guid(Request.QueryString["DeviceID"]));

        device.TownBasicID = ddlTownBasic.SelectedValue;
        device.DeviceClass = DeviceClassList.SelectedValue;
        device.DeviceName = DeviceName.Text;
        device.DeviceModel = DeviceModel.Text;
        device.DeviceCount = int.Parse(DeviceCount.Text);
        device.UnitName = UnitNameList.SelectedValue;
        device.Parameters = Parameters.Text;
        device.Price = decimal.Parse(Price.Text);
        device.DatePurchase = DateTime.Parse(DatePurchase.Text);
        device.DateUse = DateTime.Parse(DateUse.Text);
        device.DateProduct = DateTime.Parse(DateProduct.Text);
        device.Manufacturer = Manufacturer.Text;
        device.State = StateList.SelectedValue;
        device.TimeLastModified = DateTime.Now;


        //添加照片--数据库
        TownPicsInfo pic = new TownPicsInfo();
        pic.id = Guid.NewGuid();
        pic.TownBasicInfoID = device.ID;

        //保存图片
        if (WordFile.FileName.Length > 0)
        {
            HttpFileCollection files = HttpContext.Current.Request.Files;
            HttpPostedFile file = files.Get("ctl00$ContentPlaceHolder1$Picture");
            string path = string.Empty;
            string picName = DateTime.Now.ToString("yyyyMMddHHmmssff");
            bool img = SaveImg(picName, "5", file, out path);
            if (!img)
                return ;
            else
            {
                pic.PicDescript = "";
                pic.PicPath = path;
                pic.TownPicstypeID = "h";
                bool b1 = TownPics.Insert(pic);
                if (!b1)
                {

                    string allPath = Request.MapPath("") + "\\" + @path;
                    try
                    {
                        File.Delete(allPath);
                    }
                    catch
                    { }
                    Response.Write("<script language=javascript>alert('图片上传失败！')</script>");
                    return ;
                }
            }
            device.Picture = path;
        }
        bool b_up = TownDevices.Update(device);
        //EventLogInfo log = new EventLogInfo();
        //log.EventTime = DateTime.Now;
        //log.EventType = 1;
        //log.EventData = "更新记录";
        //log.ItemID = Request.QueryString["DeviceID"];
        //log.ItemName = "Devices";
        //log.ItemFullUrl = "DeviceNew.aspx";
        //log.CreatedBy = Context.User.Identity.Name;
        //log.CreatedTime = DateTime.Now;
        //log.UserIP = Request.UserHostAddress;
        //EventLog.Insert(log);
        if (b_up)
        Prompt.Text = "提示：更新成功！";
        else
            Prompt.Text = "提示：更新失败！";
    }
    //保存
    protected void ButtonSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request.QueryString["DeviceID"] == null)
                Insert();
            else
                Update();
        }
        catch (Exception ex)
        {
            Prompt.Text = "错误：" + ex.Message;
        }
    }
    protected void DepartmentList_TextChanged(object sender, EventArgs e)
    {
        DepartmentListBind();
    }

   /// <summary>
   /// 绑定县
   /// </summary>
    void DepartmentListBind()
    {
        UnitList.Items.Clear();
        string strWhere = "DepartmentID like '" + DepartmentList.SelectedValue.Substring(0, 4) + "2%' and   SUBSTRING(DepartmentID, 5, 1)<>'0' ";
        List<DepartmentInfo> list= Department.GetList(strWhere);
        foreach (DepartmentInfo dpt in list)
        {
            dpt.ShortName = dpt.ShortName.Replace("消防科", "");
            dpt.ShortName = dpt.ShortName.Replace("大队", "");
            dpt.ShortName = dpt.ShortName.Replace("消防", "");
        }
        UnitList.DataSource =list;
        UnitList.DataBind();
        BingDDLBasicInfo();
    }

    /// <summary>
    /// 绑定消防队
    /// </summary>
    void BingDDLBasicInfo()
    {
        ddlTownBasic.Items.Clear();
        string strWhere = " DepartmentID='" + UnitList .SelectedValue.ToString()+ "'";
        List<TownBasicInfo> list = TownBasic.GetList(strWhere);
        if (list.Count == 0)
        {
            ButtonSave.Enabled = false;
            Prompt.Text = "错误：没有可添加信息的消防队，请先添加此地区消防队。";
            ddlTownBasic.Items.Add("此地区没有消防队");

            string colorStr = System.Drawing.ColorTranslator.ToHtml(Color.Red);
            ddlTownBasic.Items[0].Attributes.Add("style", "color:" + colorStr);

            return;
        }
        else
        {
            ButtonSave.Enabled = true;
            Prompt.Text = "";
            ddlTownBasic.DataSource = list;
            ddlTownBasic.DataBind();
        }
    }

    protected void DeviceTypeList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindClass();
    }
    /// <summary>
    /// 绑定器材类别
    /// </summary>
    private void BindClass()
    {
        DeviceClassList.DataTextField = "ItemName";
        DeviceClassList.DataValueField = "ItemID";
        DeviceClassList.DataSource = CodeItem.GetList(" parentID='" + DeviceTypeList.SelectedValue + "' order by ItemID,SeqID ");
        DeviceClassList.DataBind();
    }

    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="name1">图片名称，不包含扩展名</param>
    /// <param name="typepath">图片分类目录TownItems表id</param>
    /// <param name="localPath">返回站点相对路径和文件名</param>
    /// <param name="postedFile">单独文件上传流</param>
    /// <returns></returns>
    private bool SaveImg(string name1, string typepath, HttpPostedFile postedFile, out string localPath)
    {
        //HttpFileCollection files = HttpContext.Current.Request.Files;
        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();

        bool fileOk = false;



        //HttpPostedFile postedFile = files[0];

        string fileName, fileExtension;
        fileName = System.IO.Path.GetFileName(postedFile.FileName);
        if (fileName != "")
        {
            fileExtension = System.IO.Path.GetExtension(fileName);
            String[] allowedExtensions = { ".jpg" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension.ToLower() == allowedExtensions[i])
                {
                    fileOk = true;
                    break;
                }
            }
        }
        if (fileOk)
        {

            //Bitmap bm = new Bitmap(path);
            //本地image文件夹路径
            string sPath = System.Web.HttpContext.Current.Request.MapPath("UpLoadImages\\" + typepath + "\\");
            //文件扩展名
            fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
            //随机文件名
            Random rnd = new Random();
            // string newName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + rnd.Next(1000).ToString();
            string newName = name1;
            localPath = "UpLoadImages\\" + typepath + "\\" + newName + fileExtension;
            // postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/") + newName + fileExtension);

            // Bitmap bmp = new Bitmap(postedFile.InputStream);



            double width = 1024;
            double height = 768;
            //从文件取得图片对象
            System.Drawing.Image image = System.Drawing.Image.FromStream(postedFile.InputStream);
            System.Double NewWidth, NewHeight;

            if (image.Width > image.Height)
            {
                NewWidth = width;
                NewHeight = image.Height * (NewWidth / image.Width);
            }
            else
            {
                NewHeight = height;
                NewWidth = (NewHeight / image.Height) * image.Width;
            }

            if (NewWidth > width)
            {
                NewWidth = width;
            }
            if (NewHeight > height)
            {
                NewHeight = height;
            }

            //取得图片大小
            System.Drawing.Size size = new Size((int)NewWidth, (int)NewHeight);
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width, size.Height);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空一下画布
            g.Clear(System.Drawing.Color.White);
            //在指定位置画图
            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
            new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
            System.Drawing.GraphicsUnit.Pixel);

            //保存高清晰度的缩略图
            bitmap.Save(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages\\" + typepath + "\\") + newName + fileExtension, ImageFormat.Jpeg);

            // bmp.Save(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/") + newName + fileExtension, ImageFormat.Jpeg);


            return true;

        }
        else
        {
            //提示
            localPath = "";
            return false;
        }

    }
    protected void UnitList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BingDDLBasicInfo();
    }
}
